﻿#ifndef USB_SERVER_H
#define USB_SERVER_H

#include "libdaq/backend/backend_option.h"
#include "libdaq/backend/usb/usb_backend.h"

namespace libdaq {
namespace backend {
using DeviceAddress = uint8_t;
using BusNumber = uint8_t;

// 定义最大总线和设备数量
constexpr uint8_t MAX_BUS_COUNT = 16;
constexpr uint8_t MAX_DEVICES_PER_BUS = 16;

// 定义设备结构体
struct DeviceInfo {
    DeviceAddress address;
    LockzhinerUSBBackend* backend;
    bool used;  // 标记设备是否已被使用
};

// 定义总线结构体
struct BusInfo {
    BusNumber number;
    DeviceInfo devices[MAX_DEVICES_PER_BUS];
    uint8_t device_count;
    bool used;  // 标记总线是否已被使用
};

class LockzhinerUSBServer {
public:
    explicit LockzhinerUSBServer(const USBOption &option);
    ~LockzhinerUSBServer();

    void StartSearch();
    
    // 使用固定大小数组的函数
    uint8_t GetBusNumbers(uint8_t* bus_numbers, uint8_t max_count) const;
    uint8_t GetDeviceAddresses(BusNumber bus_number, uint8_t* device_addresses, uint8_t max_count) const;
    
    // 保留原有函数以保持兼容性
    std::vector<BusNumber> GetBusNumbers() const; // NOLINT(*-use-nodiscard)
    std::vector<DeviceAddress> GetDeviceAddresses(BusNumber bus_number) const; // NOLINT(*-use-nodiscard)
    
    LockzhinerUSBBackend* GetClient(BusNumber, DeviceAddress);

private:
    USBOption usb_option_;
    BusInfo buses_[MAX_BUS_COUNT];  // 固定大小的总线数组
    uint8_t bus_count_;  // 当前使用的总线数量
    
    // 辅助函数
    BusInfo* FindBus(BusNumber bus_number);
    const BusInfo* FindBus(BusNumber bus_number) const;
    DeviceInfo* FindDevice(BusInfo* bus, DeviceAddress device_address);
    const DeviceInfo* FindDevice(const BusInfo* bus, DeviceAddress device_address) const;
    void AddBus(BusNumber bus_number);
    void AddDevice(BusInfo* bus, DeviceAddress device_address, LockzhinerUSBBackend* backend);
};
}
}

#endif //USB_SERVER_H
